package com.cc.springbootvalidatedemo.controller;

import com.cc.springbootvalidatedemo.utils.ValidPhone;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, Object> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error -> {
                    String field = error.getField();
                    String[] split = field.split("\\.");
                    errors.put("code", Integer.valueOf(split[1]));
                    errors.put("msg", error.getDefaultMessage());
                    errors.put("data", null);
                }
        );
        return ResponseEntity.badRequest().body(errors);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Map<String, Object>> handleConstraintViolation(ConstraintViolationException ex) {
        Map<String, Object> errors = new HashMap<>();
        ex.getConstraintViolations().forEach(violation -> {
            String field = violation.getPropertyPath().toString();
            String message = violation.getMessage();
            // 获取自定义注解中的code
            ValidPhone validPhone = violation.getConstraintDescriptor().getAnnotation().annotationType().getAnnotation(ValidPhone.class);
            if (validPhone != null) {
                int code = validPhone.code();
                // 构建包含错误码和消息的条目
                errors.put(field, Map.of("code", code, "message", message));
            } else {
                errors.put(field, message);
            }
        });
        return ResponseEntity.badRequest().body(errors);
    }
}
